jQuery(function($){
  // create todo
  $("div#todo-app input#new-todo").keydown(function() {
  	 if (event.keyCode == "13") {//keyCode=13是回车键
  		 var todoCreateTemp = JST['ruiqu/todos/create']
  		 var csrf = $("input#js-todo-index-csrf").val();
  		 var content = $(this).val();
       var _this = this
  		 $.ajax({
  			 url: "/api/todos",
  			 method: "post",
  			 headers: {
           'X-CSRF-Token': csrf
         },
  			 data: {content: content},
  			 success: function(data){
  				//  $("ul#todo-list").prepend(todoCreateTemp(data))
           $("button.js-todo-unfinish-list").click();
           $(_this).val("");
  			 }
  		 })
  	 }
  });

  // click todo checkbox
  $(document).on("click", "input.js-todo-checkbox", function(){
  	var id = $(this).data("id");
  	$("li#js-todo-li-"+ id).toggleClass("todo-done");
  	getTodoCheckedLength();
  })

  // hover event
  $(document).on({
      mouseenter: function(){
          $(this).addClass("todo-hover")
      },
      mouseleave: function(){
          $(this).removeClass("todo-hover")
      }
  }, 'li.js-todo-item');

  // done todo event
  $(document).on("click", "i.js-todo-trash-icon", function(){
  	var id = $(this).data("id");
  	var csrf = $("input#js-todo-index-csrf").val();
  	$.ajax({
  		url: "/api/todos/"+ id + "/toggle",
  		method: "put",
  		headers: {
  			'X-CSRF-Token': csrf
  		},
  		success: function(data){
  			if(data.status == true){
  				$("li#js-todo-li-"+id).remove();
          getTodoCheckedLength();
  			}
  		}
  	})
  })

  //delete todo event
  $(document).on("click", "i.js-todo-trash", function(){
  	var id = $(this).data("id");
  	var csrf = $("input#js-todo-index-csrf").val();
  	$.ajax({
  		url: "/api/todos/"+ id,
  		method: "delete",
  		headers: {
  			'X-CSRF-Token': csrf
  		},
  		success: function(data){
  			if(data.status == true){
  				$("li#js-todo-li-"+id).remove();
          getTodoCheckedLength();
  			}
  		}
  	})
  })

  //　change todo to editing
  $(document).on("click", "span.js-todo-content", function(){
		var id = $(this).data("id");
		$("li#js-todo-li-"+id).addClass("editing");
		$("input.js-edit-todo-input").focus()
	})

  // lose focus(blur) to update change
	$(document).on("blur", "input.js-edit-todo-input", function(){
		var csrf = $("input#js-todo-index-csrf").val();
		var content = $(this).val();
		var id = $(this).data("id");
		$.ajax({
			url: "/api/todos/"+ id,
			method: "put",
			headers: {
				'X-CSRF-Token': csrf
			},
			data: {content: content},
			success: function(data){
				if(data.status == true){
					$("li#js-todo-li-"+id).removeClass("editing");
					$("div.js-todo-view-"+ id +" span").text(content);
				}
			}
		})
	});

})//end jquery



function getTodoCheckedLength(){
  var checkedLength = $("div#todo-app input.js-todo-checkbox:checked").length
  if(checkedLength > 0){
    $("span.js-todo-done-number").text(checkedLength)
    $("a.js-clear-todo").show();
  }else {
    $("a.js-clear-todo").hide();
  }
}
